package com.leochin.leoplayer;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainActivity extends Activity implements SurfaceHolder.Callback,OnPreparedListener,OnVideoSizeChangedListener,OnCompletionListener{

	private SurfaceView mSurface;
	private SurfaceHolder mHolder;
	private MediaPlayer mPlayer;
	private int mVideoHeight;
	private int mVideoWidth;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mSurface = (SurfaceView) findViewById(R.id.surface);
		mHolder = mSurface.getHolder();
		mHolder.addCallback(this);
		//initSurface();
	}


	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
		String path = "http://www.mofunenglish.com/storage/pool0/video/106/178/2014052716540171923.webm";
		// "http://192.168.1.108:8080/yang.mp4"
		Uri uri = Uri.parse(path);
		
		try {
			mPlayer = new MediaPlayer();
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);	
			mPlayer.setDataSource(this, uri);		
			mPlayer.setDisplay(mHolder);
			//mPlayer.prepare();
			mPlayer.prepareAsync();
			mPlayer.setOnVideoSizeChangedListener(this);
			mPlayer.setOnPreparedListener(this);
			mPlayer.setOnCompletionListener(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
	}
	

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mPlayer == null) {
			return;
		}
		if (mPlayer.isPlaying()) {
			mPlayer.stop();
		}

		mPlayer.release();
	}


	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		Log.d("leochin","onPrepared called");
		mHolder.setFixedSize(mVideoWidth, mVideoHeight);
		mp.start();
	}


	@Override
	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		// TODO Auto-generated method stub
		
		if(width == 0 || height == 0){
			return;
		}
		
		mVideoHeight = height;
		mVideoWidth = width;	
		
		Log.d("leochin","height = " + height+",width = " + width);
	}


	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		Log.d("leochin","onCompletion called");
	}

}
